package com.mzj.saas.commons;

import org.apache.commons.lang3.math.NumberUtils;

import java.util.Random;
import java.util.UUID;

/**
 * @ClassName NonceUtil
 * @Author: zhanghy
 * @Description: TODO
 * @Date: 2018/9/21 13:58
 * @Version: 1.0
 * @Modificd By:
 */

public class NonceUtil {

    private static int randomLength = 16;

    static {
        String nonceRandomLength = "16";
        if (NumberUtils.isDigits(nonceRandomLength)) {
            randomLength = NumberUtils.toInt(nonceRandomLength);
        }
    }

    /**
     * 随机字符串
     */
    public static String randomToUUID(){
        return UUID.randomUUID().toString();
    }

    /**
     * 随机字符串
     */
    public static String randomNonce(){
        return randomNonce(randomLength);
    }

    /**
     * 随机字符串
     */
    public static String randomNonce(int length){
        String nonceStr = "";
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");

        Random random = new Random();
        for (int i = 0; i < length; i++) {
            int j = random.nextInt(uuid.length());
            nonceStr += uuid.substring(j, j + 1);
        }
        return nonceStr;
    }

}
